/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */

// 题目链接：https://leetcode.cn/problems/binary-tree-zigzag-level-order-traversal/description/

class Solution
{
public:
    vector<vector<int>> zigzagLevelOrder(TreeNode *root)
    {
        vector<vector<int>> ret;
        queue<TreeNode *> q;
        if (root == nullptr)
            return ret;
        q.push(root);
        int level = 1;
        while (q.size()) // 直到队列为空
        {
            vector<int> tmp;   // 每一层的节点内数据
            int sz = q.size(); // 记录当前层节点个数
            while (sz--)       // 将一层的节点其孩子节点全部入队列
            {
                TreeNode *t = q.front();
                tmp.push_back(t->val); // 记录当前层的数据
                q.pop();
                if (t->left)
                    q.push(t->left);
                if (t->right)
                    q.push(t->right);
            }
            if (level % 2 == 0)
                reverse(tmp.begin(), tmp.end()); // 偶数层逆序
            ret.push_back(tmp);
            level++;
        }
        return ret;
    }
};